// src/pages/CategoryDetail.js - 分区详情页面

import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Typography, Card, List, Space, Tag, Button, Select, Input, Row, Col,
  Statistic, Avatar, Tooltip, message, Badge, Spin, Empty, Divider
} from 'antd';
import {
  DatabaseOutlined, SearchOutlined, SortAscendingOutlined,
  FileOutlined, DownloadOutlined, EyeOutlined, LikeOutlined,
  StarOutlined, CloudUploadOutlined, CalendarOutlined, FilterOutlined
} from '@ant-design/icons';
import { categories, torrents } from '../services';

const { Title, Text, Paragraph } = Typography;
const { Option } = Select;
const { Search } = Input;

const CategoryDetail = () => {
  const { categoryName } = useParams();
  const navigate = useNavigate();
  const [category, setCategory] = useState(null);
  const [categoryTorrents, setCategoryTorrents] = useState([]);
  const [filteredTorrents, setFilteredTorrents] = useState([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [sortBy, setSortBy] = useState('uploadTime');
  const [sortOrder, setSortOrder] = useState('desc');
  const [messageApi, contextHolder] = message.useMessage();

  const sortOptions = [
    { value: 'uploadTime', label: '上传时间' },
    { value: 'downloadCount', label: '下载次数' },
    { value: 'size', label: '文件大小' },
    { value: 'seeders', label: '做种数' },
    { value: 'likeCount', label: '点赞数' }
  ];

  useEffect(() => {
    loadCategoryDetail();
  }, [categoryName]);

  useEffect(() => {
    filterAndSortTorrents();
  }, [categoryTorrents, searchQuery, sortBy, sortOrder]);

  const loadCategoryDetail = async () => {
    try {
      setLoading(true);

      // 获取分区信息
      const categoriesResponse = await categories.getCategories();
      if (categoriesResponse.success) {
        const categoryData = categoriesResponse.data.categories.find(
          cat => cat.name === decodeURIComponent(categoryName)
        );

        if (!categoryData) {
          messageApi.error('分区不存在');
          navigate('/resources');
          return;
        }

        setCategory(categoryData);
      }

      // 获取该分区的所有种子
      const torrentsResponse = await torrents.getTorrents();
      if (torrentsResponse.success) {
        const torrentsList = (torrentsResponse.data.torrents || [])
          .filter(torrent => torrent.category === decodeURIComponent(categoryName));
        setCategoryTorrents(torrentsList);
      }

    } catch (error) {
      console.error('加载分区详情失败:', error);
      messageApi.error('加载分区详情失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  const filterAndSortTorrents = () => {
    let filtered = [...categoryTorrents];

    // 搜索过滤
    if (searchQuery) {
      filtered = filtered.filter(torrent =>
        torrent.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
        (torrent.description && torrent.description.toLowerCase().includes(searchQuery.toLowerCase()))
      );
    }

    // 排序
    filtered.sort((a, b) => {
      let aValue = a[sortBy] || 0;
      let bValue = b[sortBy] || 0;

      if (sortBy === 'uploadTime') {
        aValue = new Date(aValue).getTime();
        bValue = new Date(bValue).getTime();
      }

      if (sortOrder === 'desc') {
        return bValue - aValue;
      } else {
        return aValue - bValue;
      }
    });

    setFilteredTorrents(filtered);
  };

  const handleTorrentClick = (torrent) => {
    navigate(`/torrents/${torrent.id}`);
  };

  const formatSize = (sizeInMB) => {
    // 确保 sizeInMB 是数字类型
    const size = Number(sizeInMB);
    if (!size || isNaN(size) || size <= 0) return '0 MB';

    if (size >= 1024 * 1024) {
      return `${(size / (1024 * 1024)).toFixed(1)} TB`;
    } else if (size >= 1024) {
      return `${(size / 1024).toFixed(1)} GB`;
    } else {
      return `${size.toFixed(1)} MB`;
    }
  };

  const formatTime = (timeString) => {
    const time = new Date(timeString);
    const now = new Date();
    const diffInHours = Math.floor((now - time) / (1000 * 60 * 60));

    if (diffInHours < 1) return '刚刚';
    if (diffInHours < 24) return `${diffInHours}小时前`;
    if (diffInHours < 24 * 7) return `${Math.floor(diffInHours / 24)}天前`;
    return time.toLocaleDateString();
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '100px 0' }}>
        <Spin size="large" tip="加载分区详情..." />
      </div>
    );
  }

  if (!category) {
    return (
      <div style={{ textAlign: 'center', padding: '100px 0' }}>
        <Empty description="分区不存在" />
      </div>
    );
  }

  return (
    <div style={{ background: '#f0f2f5', minHeight: 'calc(100vh - 200px)' }}>
      {contextHolder}
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '24px' }}>
        {/* 返回按钮 */}
        <div style={{ marginBottom: 16 }}>
          <Button
            type="link"
            icon={<DatabaseOutlined />}
            onClick={() => navigate('/resources')}
            style={{ padding: 0 }}
          >
            返回资源中心
          </Button>
        </div>

        {/* 分区信息头部 */}
        <Card style={{ marginBottom: 24 }}>
          <Row gutter={24} align="middle">
            <Col span={4}>
              <Avatar
                size={80}
                style={{ backgroundColor: category.color }}
                icon={<DatabaseOutlined />}
              />
            </Col>
            <Col span={20}>
              <Title level={2} style={{ margin: 0, color: category.color }}>
                {category.name}
              </Title>
              <Paragraph style={{ marginTop: 8 }}>
                {category.description}
              </Paragraph>
              <Space>
                <Statistic
                  title="资源数量"
                  value={categoryTorrents.length}
                  prefix={<FileOutlined />}
                />
                <Statistic
                  title="总下载量"
                  value={categoryTorrents.reduce((sum, t) => sum + (t.downloadCount || 0), 0)}
                  prefix={<DownloadOutlined />}
                />
              </Space>
            </Col>
          </Row>
        </Card>

        {/* 搜索和过滤工具栏 */}
        <Card style={{ marginBottom: 24 }}>
          <Row gutter={16}>
            <Col span={12}>
              <Search
                placeholder="搜索资源..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                allowClear
              />
            </Col>
            <Col span={6}>
              <Select
                value={sortBy}
                onChange={setSortBy}
                style={{ width: '100%' }}
                placeholder="排序方式"
              >
                {sortOptions.map(option => (
                  <Option key={option.value} value={option.value}>
                    {option.label}
                  </Option>
                ))}
              </Select>
            </Col>
            <Col span={6}>
              <Select
                value={sortOrder}
                onChange={setSortOrder}
                style={{ width: '100%' }}
              >
                <Option value="desc">降序</Option>
                <Option value="asc">升序</Option>
              </Select>
            </Col>
          </Row>
        </Card>

        {/* 资源列表 */}
        <Card>
          <List
            dataSource={filteredTorrents}
            locale={{
              emptyText: <Empty description="该分区暂无资源" />
            }}
            renderItem={torrent => (
              <List.Item
                style={{ cursor: 'pointer' }}
                onClick={() => handleTorrentClick(torrent)}
                actions={[
                  <Space key="stats">
                    <Text>{formatSize(torrent.size)}</Text>
                    <Text>下载: {torrent.downloadCount || 0}</Text>
                    <Text>S: {torrent.seeders || 0}</Text>
                    <Text>L: {torrent.leechers || 0}</Text>
                  </Space>
                ]}
              >
                <List.Item.Meta
                  avatar={<Avatar icon={<FileOutlined />} />}
                  title={torrent.name}
                  description={
                    <Space>
                      <Text>上传: {formatTime(torrent.uploadTime)}</Text>
                      <Text>上传者: {torrent.uploaderName}</Text>
                    </Space>
                  }
                />
              </List.Item>
            )}
          />
        </Card>
      </div>
    </div>
  );
};

export default CategoryDetail;